package com.lin.sqltool.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lin.sqltool.model.DatabaseInfoModel;


import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 用于数据库信息简化
 */
public class DatabaseInfoSimplifyUtil {

    private final static Map<String, String> REPLACE_MAP = new LinkedHashMap<String ,String>(){
        {

            put(",\"primaryKey\":false", "");
            put(",\"primaryKey\":true", ",\"primaryKey\":t");


            put("\"name\":", "\"n\":");
            put("\"type\":", "\"t\":");
            put("\"primaryKey\":", "\"k\":");
            put("\"tables\":", "\"t\":");
            put("\"fields\":", "\"f\":");
            put("\"comment\":", "\"c\":");


            put(":\"VARCHAR\"", ":\"VC\"");
            put(":\"varchar", ":\"VC");
            put(":\"DOUBLE\"", ":\"DB\"");
            put(":\"CHAR\"", ":\"C\"");
            put(":\"DATETIME\"", ":\"DT\"");
            put(":\"BIGINT\"", ":\"BI\"");
            put(":\"DECIMAL\"", ":\"DCM\"");
            put(":\"TEXT\"", ":\"T\" ");
            put(":\"TIMESTAMP\"", ":\"TS\"");
            put(":\"DATE\"", ":\"D\"");


            put("}", "");
            put("{", "");
            put("\"", "");
        }
    };


    /**
     * 简化
     * @param databaseModel
     */
    public static String simplify(DatabaseInfoModel databaseModel) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        StringBuilder json = new StringBuilder(objectMapper.writeValueAsString(databaseModel));
        REPLACE_MAP.entrySet().stream().forEach(entry -> {
            int index = 0;
            while ((index = json.indexOf(entry.getKey(), index)) != -1) {
                json.replace(index, index + entry.getKey().length(), entry.getValue());
                index += entry.getValue().length();
            }
        });
        return json.toString();
    }
}
